<template>
  <div class="address-management page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">地址管理</h1>
        <p class="page-subtitle">管理系统地址信息，支持按字母排序和快速定位</p>
      </div>
    </div>

    <div class="content-card">
      <div class="search-section">
        <el-input
          v-model="searchForm.areaName"
          placeholder="地区名称"
          class="search-input"
          clearable
        />
        <el-select
          v-model="searchForm.areaLevel"
          placeholder="地区级别"
          clearable
          class="level-select"
        >
          <el-option label="省份" :value="1" style="selected" />
          <el-option label="市" :value="2" />
          <el-option label="区县" :value="3" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <!-- 字母导航 -->
      <div class="alphabet-nav">
        <div
          v-for="letter in alphabetList"
          :key="letter"
          class="alphabet-item"
          :class="{ active: currentLetter === letter }"
          @click="scrollToLetter(letter)"
        >
          {{ letter }}
        </div>
      </div>

      <div class="address-list" ref="addressListRef">
        <div
          v-for="(group, letter) in groupedAddresses"
          :key="letter"
          :id="`letter-${letter}`"
          class="letter-group"
        >
          <div class="letter-header">
            <h3 class="letter-title">{{ letter }}</h3>
            <span class="letter-count">({{ group.length }}个)</span>
          </div>

          <div class="address-grid">
            <div
              v-for="address in group"
              :key="address.id"
              class="address-item"
              :class="{ disabled: address.isOpen === 0 }"
            >
              <div class="address-info">
                <div class="address-name">{{ address.areaName }}</div>
                <div class="address-details">
                  <span class="area-code">编码: {{ address.areaCode }}</span>
                  <span v-if="address.cityCode" class="city-code">
                    城市码: {{ address.cityCode }}
                  </span>
                </div>
                <div class="address-level">
                  <el-tag
                    :type="getLevelTagType(address.areaLevel)"
                    size="small"
                  >
                    {{ getLevelText(address.areaLevel) }}
                  </el-tag>
                </div>
              </div>

              <div class="address-actions">
                <el-switch
                  v-model="address.isOpen"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleToggleOpen(address)"
                  :loading="address.loading"
                />
                <span class="status-text">
                  {{ address.isOpen === 1 ? "已开启" : "已关闭" }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { postWithAuth } from "@/utils/request";

// 类型定义
interface AddressInfo {
  id: number;
  areaCode: string;
  areaName: string;
  areaLevel: string;
  cityCode: string;
  parentId: number;
  isOpen: number;
  loading?: boolean;
}

const loading = ref(false);
const addressList = ref<AddressInfo[]>([]);
const currentLetter = ref("A");
const addressListRef = ref<HTMLElement>();

// 搜索表单
const searchForm = ref({
  areaLevel: "", // 默认选择省份
  parentId: "",
  areaName: "",
});

// 字母列表
const alphabetList = ref<string[]>([]);

// 获取地区级别文本
const getLevelText = (level: string): string => {
  const levelMap: Record<string, string> = {
    "1": "省份",
    "2": "市",
    "3": "区县",
  };
  return levelMap[level] || "未知";
};

// 获取地区级别标签类型
const getLevelTagType = (level: string): string => {
  const typeMap: Record<string, string> = {
    "1": "primary", // 省份
    "2": "success", // 市
    "3": "warning", // 区县
  };
  return typeMap[level] || "info";
};

// 按字母分组地址
const groupedAddresses = computed(() => {
  const groups: Record<string, AddressInfo[]> = {};

  addressList.value.forEach((address) => {
    const firstChar = getFirstLetter(address.areaName);
    if (!groups[firstChar]) {
      groups[firstChar] = [];
    }
    groups[firstChar].push(address);
  });

  // 对每个字母组内的地址按名称排序
  Object.keys(groups).forEach((letter) => {
    groups[letter].sort((a, b) =>
      a.areaName.localeCompare(b.areaName, "zh-CN")
    );
  });

  return groups;
});

// 获取汉字首字母
const getFirstLetter = (str: string): string => {
  if (!str) return "#";

  const firstChar = str.charAt(0);
  const code = firstChar.charCodeAt(0);

  // 判断是否为汉字
  if (code >= 0x4e00 && code <= 0x9fff) {
    // 使用更准确的拼音首字母映射
    const pinyinMap: Record<string, string> = {
      北: "B",
      京: "J",
      上: "S",
      海: "H",
      天: "T",
      津: "J",
      河: "H",
      山: "S",
      内: "N",
      蒙: "M",
      古: "G",
      辽: "L",
      宁: "N",
      吉: "J",
      林: "L",
      黑: "H",
      龙: "L",
      江: "J",
      苏: "S",
      浙: "Z",
      安: "A",
      徽: "H",
      福: "F",
      建: "J",
      东: "D",
      南: "N",
      广: "G",
      重: "C",
      庆: "Q",
      四: "S",
      川: "C",
      贵: "G",
      州: "Z",
      云: "Y",
      藏: "Z",
      陕: "S",
      甘: "G",
      肃: "S",
      青: "Q",
      夏: "X",
      新: "X",
      疆: "J",
      台: "T",
      湾: "W",
      香: "X",
      港: "G",
      澳: "A",
      门: "M",
      湖: "H",
      西: "X", // 添加这两个汉字
    };

    return pinyinMap[firstChar] || firstChar.toUpperCase();
  }

  // 非汉字直接返回大写字母
  return firstChar.toUpperCase();
};

// 获取地址列表
const fetchAddressList = async () => {
  loading.value = true;
  try {
    const params = {
      areaLevel: searchForm.value.areaLevel || "1",
      parentId: searchForm.value.parentId || "",
      areaName: searchForm.value.areaName || "",
    };

    const res = await postWithAuth("/internal/address/areas", params);
    if (res.code === 0 && res.data) {
      addressList.value = Array.isArray(res.data) ? res.data : [];

      // 生成字母列表
      const letters = new Set<string>();
      addressList.value.forEach((address) => {
        const letter = getFirstLetter(address.areaName);
        letters.add(letter);
      });
      alphabetList.value = Array.from(letters).sort();
    } else {
      addressList.value = [];
      alphabetList.value = [];
      ElMessage.error(res.message || "获取地址列表失败");
    }
  } catch (error) {
    console.error("获取地址列表失败:", error);
    ElMessage.error("获取地址列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  fetchAddressList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    areaLevel: "",
    parentId: "",
    areaName: "",
  };
  fetchAddressList();
};

// 滚动到指定字母
const scrollToLetter = (letter: string) => {
  currentLetter.value = letter;
  const element = document.getElementById(`letter-${letter}`);
  if (element) {
    element.scrollIntoView({ behavior: "smooth" });
  }
};

// 切换开启/关闭状态
const handleToggleOpen = async (address: AddressInfo) => {
  address.loading = true;
  try {
    const response = await postWithAuth(
      `/internal/address/openOrCLose/${address.id}/${address.isOpen}`,
      {}
    );

    if (response.code === 0) {
      ElMessage.success(`地址${address.isOpen === 1 ? "开启" : "关闭"}成功`);
    } else {
      // 如果操作失败，恢复原状态
      address.isOpen = address.isOpen === 1 ? 0 : 1;
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    // 如果操作失败，恢复原状态
    address.isOpen = address.isOpen === 1 ? 0 : 1;
    console.error("切换状态失败:", error);
    ElMessage.error("操作失败");
  } finally {
    address.loading = false;
  }
};

onMounted(() => {
  fetchAddressList();
});
</script>

<style scoped>
.address-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #f3f4f6;
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 200px;
}

.level-select {
  width: 150px;
}

.alphabet-nav {
  padding: 15px 20px;
  background: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  position: sticky;
  top: 0;
  z-index: 10;
  margin-bottom: 20px; /* 添加底部边距，避免遮挡数据 */
}

.alphabet-item {
  padding: 6px 12px;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #6b7280;
  transition: all 0.2s;
}

.alphabet-item:hover {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.alphabet-item.active {
  background: #3b82f6;
  border-color: #3b82f6;
  color: white;
}

.address-list {
  max-height: 70vh;
  overflow-y: auto;
  padding-top: 10px; /* 添加顶部内边距 */
}

.letter-group {
  margin-bottom: 30px;
}

.letter-header {
  padding: 15px 20px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  gap: 10px;
  position: sticky;
  top: 5px; /* 调整位置，避免被字母导航遮挡 */
  z-index: 5;
}

.letter-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.letter-count {
  font-size: 14px;
  color: #6b7280;
}

.address-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  padding: 20px;
}

.address-item {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.2s;
}

.address-item:hover {
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

.address-item.disabled {
  background: #f9fafb;
  opacity: 0.6;
}

.address-info {
  flex: 1;
}

.address-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
}

.address-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 8px;
}

.area-code,
.city-code {
  font-size: 12px;
  color: #6b7280;
}

.address-level {
  margin-top: 8px;
}

.address-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.status-text {
  font-size: 12px;
  color: #6b7280;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .address-grid {
    grid-template-columns: 1fr;
  }

  .alphabet-nav {
    justify-content: center;
  }

  .alphabet-item {
    padding: 4px 8px;
    font-size: 12px;
  }
}
</style>
